<template>
  <div class="row mt-3">
    <div class="col-12" >
      <div class="card">
        <div class="card-body">
          <img class="mx-auto d-block" style="width: 200px;" src="../assets/images/icon.jpg" alt="Image"/>
          <form @submit.prevent="onSubmit">
            <div class="form-group">
              <label for="username">用户名</label>
              <input type="text" class="form-control" v-model="username" id="username"/>
            </div>
            <div class="form-group">
              <label for="password">密码</label>
              <input type="password" class="form-control" v-model="password" id="password"/>
            </div>
            <button type="submit" class="btn btn-block btn-success">登录</button>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Bmob from 'hydrogen-js-sdk'
// import axios from 'axios'
export default {
  name: 'Login',
  data () {
    return {
      username: '',
      password: ''
    }
  },
  methods: {
    onSubmit () {
      console.log('登录')
      Bmob.User.login(this.username, this.password).then(res => {
        console.log(res)
        const data = res
        const users = []
        console.log(data)
        for (let i in data) {
          const user = data[i]
          console.log(user)
          users.push(user)
        }
        // const result = users.filter((us) => {
        //   return us.username === this.username && us.password === this.password
        // })
        console.log(users.length)
        if (users != null && users.length > 0) {
          this.$store.dispatch('setUser', users[0].email)
          this.$router.push('/home')
        } else {
          alert('账号或者密码错误！')
        }
      }).catch(err => {
        console.log(err)
        this.$store.dispatch('setUser', null)
      })
      // axios.get('/user.json')
      //   .then((res) => {
      //     console.log(res)
      //     const data = res.data
      //     const users = []
      //     for (let key in data) {
      //       const user = data[key]
      //       console.log(user)
      //       users.push(user)
      //     }
      //     console.log(users)
      //     // 数组过滤
      //     let result = users.filter((user) => {
      //       return user.username === this.username && user.password === this.password
      //     })
      //     console.log(result)
      //     // 判断result长度是否大于0，大于封路成功
      //     if (result != null && result.length > 0) {
      //       this.$router.push('/home')
      //     } else {
      //       alert('账号或密码错误！')
      //     }
      //   })
    }
  }
}
</script>

<style lang="stylus" scoped>
  .card-body img
    width 260px
    margin 50px 0 7
    0px
  .btn
    margin 35px 0 50px
</style>
